{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python_defaultSpec_1596467253257",
   "display_name": "Python 3.7.4 64-bit ('tensorflow': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 损失函数\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(), dtype=float32, numpy=1.3862944>"
     },
     "metadata": {},
     "execution_count": 2
    }
   ],
   "source": [
    "# 分类问题的交叉熵 - 四分类\n",
    "# 参数:1 -真实one-hot, 2-预测概率\n",
    "tf.losses.categorical_crossentropy([0,1,0,0],[0.25,0.25,0.25,0.25])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(), dtype=float32, numpy=2.3978953>"
     },
     "metadata": {},
     "execution_count": 3
    }
   ],
   "source": [
    "# 预测错了交叉熵变大\n",
    "tf.losses.categorical_crossentropy([0,1,0,0],[0.1,0.1,0.8,0.1])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(), dtype=float32, numpy=0.030459179>"
     },
     "metadata": {},
     "execution_count": 4
    }
   ],
   "source": [
    "# 预测成功 结果很小\n",
    "tf.losses.categorical_crossentropy([0,1,0,0],[0.01,0.97,0.01,0.01])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "<tf.Tensor: shape=(), dtype=float32, numpy=2.3025842>"
     },
     "metadata": {},
     "execution_count": 5
    }
   ],
   "source": [
    "# 二分类\n",
    "tf.losses.binary_crossentropy([1],[0.1])  # 预测失败 结果很大"
   ]
  }
 ]
}